package com.yugao.fintech.antelope.base.ram;

import org.apache.commons.lang3.RegExUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;

public class RequestMappingUtils {
    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");

    private static final String ASTERISK = "*";

    /**
     * 获取映射的路径
     */
    public static List<String> getMappingPath(Annotation annotation, RequestMappingInfo info) {
        List<String> path = new ArrayList<>();
        Optional.ofNullable(annotation).ifPresent(anonymous -> {
            if (Objects.nonNull(info.getPatternsCondition())) {
                info.getPatternsCondition().getPatterns()
                        .forEach(url -> path.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK)));
            } else if (Objects.nonNull(info.getPathPatternsCondition())) {
                info.getPathPatternsCondition().getPatterns()
                        .forEach(url -> path.add(RegExUtils.replaceAll(url.getPatternString(), PATTERN, ASTERISK)));
            }
        });
        return path;
    }
}
